package logic

import (
	"context"
	"database/sql"

	"mail/service/property/rpc/internal/svc"
	"mail/service/property/rpc/property"

	"github.com/dtm-labs/dtmcli"
	"github.com/dtm-labs/dtmgrpc"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type CurtailStockLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCurtailStockLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CurtailStockLogic {
	return &CurtailStockLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 减缩
func (l *CurtailStockLogic) CurtailStock(in *property.StockRequest) (*property.StockResponse, error) {
	// todo: add your logic here and delete this line
	//获取数据库连接
	db, err := sqlx.NewMysql(l.svcCtx.Config.Mysql.DataSource).RawDB()
	if err != nil {
		return nil, status.Error(500, err.Error())
	}
	//获得子事务屏障对象
	barrier, err := dtmgrpc.BarrierFromGrpc(l.ctx)
	if err != nil {
		return nil, status.Error(500, err.Error())
	}
	//开启子事务屏障
	err = barrier.CallWithDB(db, func(tx *sql.Tx) error {
		// 正好，更新资产库存
		sharp, err := l.svcCtx.PropertyModel.TxAdjustStock(tx, in.Id, -1)
		if err != nil {
			return err
		}
		affected, err := sharp.RowsAffected()
		//库存不足，返回子事务失败
		if err == nil && affected == 0 {
			return dtmcli.ErrFailure
		}
		return err
	})

	//这种情况是库存不足，不在重试，走回滚
	if err == dtmcli.ErrFailure {
		return nil, status.Error(codes.Aborted, dtmcli.ResultFailure)
	}
	if err != nil {
		return nil, err
	}
	//人为制造异常失败，方便测试
	//return nil,status.Error(codes.Aborted,dtmcli.ResultFailure)
	return &property.StockResponse{}, nil
}
